package com.example.hello.controller;

import com.example.hello.common.Result;
import com.example.hello.service.FileStorageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "文件管理", description = "文件上传下载相关接口")
@RestController
@RequestMapping("/api/file")
public class FileController {

    private static final Logger logger = LogManager.getLogger(FileController.class);

    @Autowired
    private FileStorageService fileStorageService;

    @Operation(summary = "上传用户头像", description = "上传用户头像图片")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "上传成功"),
            @ApiResponse(responseCode = "500", description = "上传失败")
    })
    @PostMapping("/avatar")
    public Result<String> uploadAvatar(
            @Parameter(description = "头像文件", required = true) @RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error(400, "请选择文件");
            }
            
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error(400, "只能上传图片文件");
            }
            
            // 验证文件大小（限制为2MB）
            if (file.getSize() > 2 * 1024 * 1024) {
                return Result.error(400, "文件大小不能超过2MB");
            }
            
            String fileUrl = fileStorageService.uploadFile(file, "avatars");
            return Result.success(fileUrl);
        } catch (IOException e) {
            logger.error("头像上传失败", e);
            
            // 返回更详细的错误信息
            return Result.error(500, "头像上传失败: " + e.getMessage());
        }
    }

    @Operation(summary = "上传景点图片", description = "上传景点相关图片")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "上传成功"),
            @ApiResponse(responseCode = "500", description = "上传失败")
    })
    @PostMapping("/attraction")
    public Result<Map<String, String>> uploadAttractionImages(
      @Parameter(description = "景点图片", required = true) 
      @RequestParam("files") List<MultipartFile> files) {
        try {
            if (files.isEmpty()) {
                return Result.error(400, "请选择文件");
            }
            
            // 验证文件数量
            if (files.size() > 10) {
                return Result.error(400, "一次最多上传10张图片");
            }
            
            // 验证每个文件
            for (MultipartFile file : files) {
                // 验证文件类型
                String contentType = file.getContentType();
                if (contentType == null || !contentType.startsWith("image/")) {
                    return Result.error(400, "只能上传图片文件");
                }
                
                // 验证文件大小（限制为5MB）
                if (file.getSize() > 5 * 1024 * 1024) {
                    return Result.error(400, "每个文件大小不能超过5MB");
                }
            }
            
            Map<String, String> fileUrls = fileStorageService.uploadFiles(files, "attractions");
            return Result.success(fileUrls);
        } catch (IOException e) {
            logger.error("景点图片上传失败", e);
            
            // 临时返回模拟URL
            Map<String, String> mockUrls = new HashMap<>();
            for (MultipartFile file : files) {
                mockUrls.put(file.getOriginalFilename(), 
                        "https://example.com/mock-attraction-" + System.currentTimeMillis() + "-" + file.getOriginalFilename());
            }
            return Result.success(mockUrls);
        }
    }

    @Operation(summary = "删除文件", description = "根据文件URL删除文件")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "500", description = "删除失败")
    })
    @DeleteMapping
    public Result<Void> deleteFile(
            @Parameter(description = "文件URL", required = true) @RequestParam("fileUrl") String fileUrl) {
        boolean success = fileStorageService.deleteFile(fileUrl);
        if (success) {
            return Result.success();
        } else {
            return Result.error(500, "文件删除失败");
        }
    }

    @Operation(summary = "获取文件访问URL", description = "获取私有文件的临时访问URL")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "500", description = "获取失败")
    })
    @GetMapping("/presigned")
    public Result<String> getPresignedUrl(
            @Parameter(description = "对象键", required = true) @RequestParam("objectKey") String objectKey,
            @Parameter(description = "过期时间（分钟）", required = false) @RequestParam(value = "expirationMinutes", defaultValue = "60") Integer expirationMinutes) {
        
        if (objectKey == null || objectKey.isEmpty()) {
            return Result.error(400, "对象键不能为空");
        }
        
        String presignedUrl = fileStorageService.generatePresignedUrl(objectKey, expirationMinutes);
        if (presignedUrl != null) {
            return Result.success(presignedUrl);
        } else {
            return Result.error(500, "生成访问URL失败");
        }
    }
} 